package org.jetlinks.pro.auth.service;

import lombok.AllArgsConstructor;
import org.hswebframework.ezorm.rdb.mapping.ReactiveRepository;
import org.hswebframework.web.bean.FastBeanCopier;
import org.hswebframework.web.system.authorization.api.entity.DimensionEntity;
import org.hswebframework.web.system.authorization.api.entity.DimensionTypeEntity;
import org.jetlinks.pro.auth.entity.OrganizationEntity;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

/**
 * 维度初始化
 * <p>
 * 实现{@link org.springframework.boot.CommandLineRunner}在项目启动时创建时创建
 * {@link org.hswebframework.web.system.authorization.api.entity.DimensionTypeEntity}
 * 的机构和角色实例.
 *
 * @author wangzheng
 * @since 1.0
 */
@Component
@AllArgsConstructor
public class DimensionInitService implements CommandLineRunner {

    private final ReactiveRepository<DimensionTypeEntity, String> dimensionTypeRepository;
    private final ReactiveRepository<DimensionEntity, String> dimensionRepository;
    private final ReactiveRepository<OrganizationEntity, String> organizationRepository;

    @Override
    public void run(String... args) {
//        DimensionTypeEntity org = new DimensionTypeEntity();
//        org.setId("org");
//        org.setName("机构");
//        org.setDescribe("机构维度");

        DimensionTypeEntity role = new DimensionTypeEntity();
        role.setId("role");
        role.setName("角色");
        role.setDescribe("角色维度");

        Mono
            .zip(
                //保存角色维度
                dimensionTypeRepository.save(role),
                //TODO 1.10版本后移除以下逻辑
                //删除动态配置的org类型
                dimensionTypeRepository.deleteById("org"),
                //同步之前的机构维度数据到机构表
                organizationRepository
                    .createQuery()
                    .count()
                    .flatMap(i -> {
                        if (i == 0) {
                            return dimensionRepository
                                .createQuery()
                                .where(DimensionEntity::getTypeId, "org")
                                .fetch()
                                .map(e -> FastBeanCopier.copy(e, new OrganizationEntity()))
                                .as(organizationRepository::save)
                                .then(
                                    dimensionRepository
                                        .createDelete()
                                        .where(DimensionEntity::getTypeId, "org")
                                        .execute()
                                );
                        }
                        return Mono.just(i);
                    })
            )
            .subscribe();

    }
}
